package com.iakuil.app.common.ws;

import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.http.HttpUtil;
import com.iakuil.app.common.core.constant.RedisConstant;
import com.iakuil.app.common.core.util.SecurityUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import java.nio.charset.Charset;
import java.util.Map;

/**
 * 握手拦截器
 *
 * <p>客户端认证
 *
 * @author Kai
 */
@Slf4j
@Component
public class WsHandshakeInterceptor implements HandshakeInterceptor {
    /**
     * 握手前
     */
    @Override
    @SuppressWarnings("NullableProblems")
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) {
        log.info("Handshake begin...");
        // 获得请求参数
        Map<String, String> paramMap = HttpUtil.decodeParamMap(request.getURI().getQuery(), Charset.defaultCharset());
        String token = paramMap.get(RedisConstant.WS_ID_ATTR_NAME);
        if (CharSequenceUtil.isBlank(token)) {
            return false;
        }

        // token换loginId，一般是uid
        Object uid = SecurityUtils.getUserIdByToken(token);
        if (uid == null) {
            return false;
        }

        // 将uid放入属性域
        attributes.put(RedisConstant.WS_ID_ATTR_NAME, uid);
        log.info("用户[{}]握手成功！", uid);
        return true;
    }

    /**
     * 握手后
     */
    @Override
    @SuppressWarnings("NullableProblems")
    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception exception) {
        log.info("Handshake complete!");
    }
}

